<?php
require_once("{$CfgPara->root}/class/user_operate.class.php");
require_once("{$CfgPara->root}/class/do_edit_img.func.php");
require_once("{$CfgPara->root}/class/mysql.func.php");
require_once("{$CfgPara->root}/class/make_img_name.class.php");

/**
 * 鞋主秀数据模型
 *
 * @version 1.0
 * @author Human
 */
class shoe_show_m
{
    //列表的内容 1代表热门 2最新 3客户 10我的鞋主秀 11作品的鞋主秀
    /**
     * 列表类型 热门
     */
    const ListHot = 1;
    /**
     * 列表类型 最新
     */
    const ListNew = 2;
    /**
     * 列表类型 客户
     */
    const ListClient = 3;

    /**
     * 列表类型 我的收藏
     */
    const ListMyCollect = 7;

    /**
     * 列表类型 我的鞋主秀
     */
    const ListMine = 10;
    /**
     * 列表类型 作品的鞋主秀 只返回最新1个
     */
    const ListForWork1 = 11;
    /**
     * 列表类型 作品的鞋主秀 返回所有
     */
    const ListForWork = 12;

    /**
     * 鞋主秀数量类型 用户自己发布
     */
    const CountMine = 1;
    /**
     * 鞋主秀数量类型 用户的所有作品的客户鞋主秀
     */
    const CountClient = 2;
    /**
     * 鞋主秀数量类型 所有
     */
    const CountAll = 0;
    /**
     * 鞋主秀数量类型 某件作品下的数量
     */
    const CountWork = 3;

    /**
     * @var int 获取鞋主秀列表时 如果设置了计算总数
     * 则为总数量，如果没设置为-1 如果计算时错误为-2
     */
    public $show_list_count;

    public function __construct($dbPara = NULL)
    {
        if ($dbPara != null) {
            db_connect($dbPara);
        }
    }

    public function show_count($type, $id)
    {
        if ($type == shoe_show_m::CountMine) //我的鞋主秀数量
        {
            $result1 = db_query("SELECT Count(*) FROM `shoe_show` WHERE `Author` = {$id}");

        } elseif ($type == shoe_show_m::CountAll) //所有鞋主秀数量
        {
            $result1 = db_query("SELECT Count(*) FROM `shoe_show`");
        } else {
            return "查询专题数量时 提交信息错误";
        }

        if ($result1 !== false) {
            $result = $result1->fetch_array();
            return $result[0];
        } else {
            return db_error();
        }
    }

    /**
     * 根据作品id与在作品的索引
     * 获取鞋秀信息 正确返回对象，错误返回错误信息
     * @param int $work_id 作品Id
     * @param int $work_index 作品的鞋主秀索引
     */
    public function show_msg2($work_id, $work_index)
    {
        if (!is_numeric($work_id) || !is_numeric($work_index)) {
            return "错误:提交的鞋主秀信息错误";
        }
        //先查询鞋主秀相关内容 避免当时作品已删除 但是鞋主秀还保留的情况
        $sql_str = "SELECT `shoe_show`.*,
				    date_format(`shoe_show`.`ReleaseDt`,'%Y.%m.%d') as ReleaseDate, 
                    `users`.`Name` as UserName, `users`.`Avatar` as UserAvatar 
                    FROM `shoe_show`,`users` 
                    WHERE `shoe_show`.`WorkId` = {$work_id} AND 
                          `shoe_show`.`WorkIndex` = {$work_index} AND 
                          `shoe_show`.`Author` = `users`.`Id` ";

        $result1 = db_query($sql_str);
        if ($result1 instanceof mysqli_result) {
            if ($result = $result1->fetch_object()) {
                //return $result;
            } else {
                return '未查询到此鞋主秀';
            }
        } else {
            return db_error();
        }
        if (!isset($result->WorkId)) return '未查询到此鞋主秀';
        //再查询鞋主秀所属作品的相关内容
        $sql_str = "SELECT `Name`,`Picture`,`Introd` 
                    FROM `works` 
                    WHERE `Id` = '{$result->WorkId}'";
        $result1 = db_query($sql_str);
        if ($result1 !== FALSE && $result1->num_rows > 0) {
            if ($result_workMsg = $result1->fetch_object()) {
                $result->WorkName = $result_workMsg->Name;
                $result->WorkPicture = $result_workMsg->Picture;
                $result->WorkIntrod = $result_workMsg->Introd;
            }
        }
        return $result;
    }

    /**
     * 获取秀的图片 返回文件名数组
     * @param string 秀的图片存储字符串
     */
    public function shoe_show_imgs($img_text)
    {
        $showImg_temp = rtrim($img_text, ';');
        $showImg_temp = explode(";", $img_text);
        $showImg_count = count($showImg_temp);
        if ($showImg_count > 9) {
            for ($i = 10; $i <= $showImg_count; $i++) {
                unset($showImg_temp[$i]);
            }
        }
        if ($showImg_count > 0) {
            return $showImg_temp;
        } else {
            return false;
        }
    }

    /**
     * 鞋主秀列表 成功返回作品对象数组 错误返回错误信息
     * @param int $type 列表的内容 1代表热门 2最新 3客户 10我的鞋主秀 11作品的鞋主秀
     * @param int $id 列表内容对应的id 热门/最新:0 客户:当前用户Id 作品的鞋主秀:作品Id 我的鞋主秀:当前用户Id
     * @param int $page 当前页索引 1最小
     * @param int $page_size 每页条目数
     * @param string $search 搜索的文本
     * @param bool $count 是否同时计算总数
     */
    function show_list($type, $id, $page, $page_size, $search = null, $count = false)
    {
        if (!is_numeric($type) || !is_numeric($id) || !is_numeric($page) || !is_numeric($page_size)) {
            return "错误:鞋主秀列表查询信息错误";
        }
        $limit_count = $page_size;
        $limit_offset = ($page - 1) * $page_size;//计算偏移量
        if ($search != null && is_string($search))  //加入全文检索语句
        {
            $search_text = urldecode($search);
            $search_text = db_escape($search_text);
            if (mb_strlen($search_text) < 2) {
                return "搜索文本长度应大于1";
            }
            if ($search_text !== false) {
                $search_sql = "AND MATCH (`shoe_show`.`Keyword`) AGAINST ('{$search_text}')";
            } else {
                $search_sql = '';
            }
        } else {
            $search_sql = '';
        }
        if ($count === true) //同时计算检索总数 而不受limit影响
        {
            $found_rows_sql = 'SQL_CALC_FOUND_ROWS';
        } else {
            $this->topic_list_count = -1;
            $found_rows_sql = '';
        }
        $sql_str = "SELECT {$found_rows_sql} `shoe_show`.*,`users`.`Name` as UserName, `users`.`Avatar` as UserAvatar ";
        if ($type == shoe_show_m::ListHot) //1热门
            $sql_str .= ",(`shoe_show`.`CommentCount`*`sys_hot_compute`.`CommentWeight`+ `shoe_show`.`UpCount`*`sys_hot_compute`.`UpWeight`) as HotPoint
                        FROM `shoe_show`,`sys_hot_compute`,`users` 
                        WHERE `shoe_show`.`Author` = `users`.`Id` AND `shoe_show`.`State` = 1
                        ORDER BY `HotPoint` DESC";
        elseif ($type == shoe_show_m::ListNew) //2最新
            $sql_str .= "FROM `shoe_show`,`users`  
                        WHERE `shoe_show`.`Author` = `users`.`Id` AND `shoe_show`.`State` = 1 {$search_sql} 
                        ORDER BY `shoe_show`.`Id` DESC";
        elseif ($type == shoe_show_m::ListClient) //3客户
        {
            if (isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id']))
                $sql_str .= "FROM `shoe_show`,`users`,`works` 
                            WHERE `works`.`Author`={$_SESSION['user_id']} 
                            AND `shoe_show`.`WorkId` = `works`.`Id` 
                            AND `shoe_show`.`Author` = `users`.`Id` 
                            AND `shoe_show`.`State` = 1
                            ORDER BY `shoe_show`.`Id` DESC";
            else {
                $result = array();
                return $result;
            }
        } elseif ($type == shoe_show_m::ListMyCollect) {
            $sql_str .= "FROM `shoe_show`,`user_collect`,`users` 
                        WHERE `shoe_show`.`Id` = `user_collect`.`CollectId` AND 
                              `user_collect`.`UserId` = `users`.`Id` AND
                              `user_collect`.`UserId` = {$_SESSION['user_id']} AND 
                              `user_collect`.`Type` = 1 {$search_sql} 
                              ORDER BY `user_collect`.`CollectDt` DESC";
        } elseif ($type == shoe_show_m::ListMine) //10我的鞋主秀
            $sql_str .= "FROM `shoe_show`,`users`  WHERE `shoe_show`.`Author` = '{$id}' AND `shoe_show`.`Author` = `users`.`Id` {$search_sql} ORDER BY `shoe_show`.`Id` DESC";
        elseif ($type == shoe_show_m::ListForWork1 || $type == shoe_show_m::ListForWork) //11作品的鞋主秀
        {
            if ($type == shoe_show_m::ListForWork1) {
                $limit_count = 1;
                $limit_offset = 0;
            }
            $sql_str .= "FROM `shoe_show`,`users` 
                        WHERE `shoe_show`.`WorkId` = '{$id}' AND `shoe_show`.`Author` = `users`.`Id` AND 
                              `shoe_show`.`State` = 1
                        ORDER BY `shoe_show`.`Id` DESC";
        } else
            return '提交的鞋主秀列表类型错误';

        $sql_str .= " LIMIT {$limit_offset},{$limit_count}";
        $result1 = db_query($sql_str);
        if ($result1 instanceof mysqli_result) {
            $fetch_result = db_fetch_list($result1, $rows);
            if ($count === true) {
                $found_count = db_query('SELECT FOUND_ROWS()');
                if ($found_count !== false) {
                    $this->show_list_count = $found_count->fetch_array()[0];
                } else {
                    $this->show_list_count = -2;
                }
            }
            return $rows;
        } else {
            return db_error();
        }
    }

    /**
     * 秀评论列表 成功返回评论对象数组 错误返回错误信息
     * @param int $show_id 作品id
     * @param int $page 当前页
     * @param int $page_size 每页条目数
     */
    function show_comment_list($show_id, $page, $page_size)
    {
        if (!is_numeric($show_id) || !is_numeric($page) || !is_numeric($page_size)) {
            return "错误:评论查询信息错误";
        }
        $limit_offset = ($page - 1) * $page_size;//计算偏移量
        $result1 = db_query("SELECT `show_comment`.*,date_format(`show_comment`.`CommentDt`,'%m.%d %H:%i') as CommentDt2, `users`.`Avatar`,`users`.`Name` as UserName FROM `show_comment`, `users` 
                                        WHERE `show_comment`.`ShowId` = '{$show_id}' AND `users`.`Id` = `show_comment`.`UserId` 
                                        ORDER BY `show_comment`.`Id` DESC LIMIT {$limit_offset},{$page_size}");
        if ($result1 instanceof mysqli_result) {
            $fetch_result = db_fetch_list($result1, $rows);
            return $rows;
        } else {
            return db_error();
        }
    }

    /**
     * 秀推荐 成功返回1 取消推荐返回-1 错误返回错误信息
     * @param int $work_id 作品Id
     */
    function show_recommend($show_id)
    {
        if (!is_numeric($show_id)) {
            return "错误:推荐信息错误";
        }
        $result = 1;
        $update_type = '+';
        db_begin();
        $result1 = db_query("INSERT INTO `show_up` SET 
                                                    `ShowId` = '{$show_id}',
                                                    `UserId` = '{$_SESSION['user_id']}'");
        if ($result1 !== true) {
            if (db_errno() === 1062) //已经推荐过 则取消推荐
            {
                $result = -1;
                $update_type = '-';
                $result2 = db_query("DELETE FROM `show_up` WHERE 
                                                `ShowId` = '{$show_id}' AND 
                                                `UserId` = '{$_SESSION['user_id']}'");
                if ($result2 !== true) {
                    return db_rollback();
                }
            } else {
                return db_rollback();
            }
        }
        $result3 = db_query("UPDATE `shoe_show` SET `UpCount` = `UpCount` {$update_type} 1 
                                           WHERE `Id` = '{$show_id}'");
        if ($result3 !== true) {
            return db_rollback();
        }
        //更新作者获得的推荐数
        $result3 = db_query("UPDATE `users`,`shoe_show` SET `users`.`HeartCount` = `users`.`HeartCount` {$update_type} 1 
                                       WHERE `users`.`Id` = `shoe_show`.`Author` AND `shoe_show`.`Id` = {$show_id}");
        if ($result3 !== true) {
            return db_rollback();
        }

        $op = new user_operate();
        $result1 = $op->operate_save($op::ShoeShowUp, $_SESSION['user_id'], $show_id);
        if ($result1 !== TRUE) {
            db_rollback();
            return $result1;
        }

        db_commit();
        return $result;
    }

    /**
     * 秀推荐人员列表 成功返回对象数组 错误返回错误信息
     * @param int $show_id 秀id
     * @param int $page 当前页
     * @param int $page_size 每页条目数
     */
    function show_recommend_list($show_id, $page, $page_size)
    {
        if (!is_numeric($show_id)) {
            return "错误:推荐信息错误";
        }
        $limit_offset = ($page - 1) * $page_size;//计算偏移量
        $result = db_query("SELECT `show_up`.*,`users`.`Name` as UserName 
                                        FROM `show_up`,`users` WHERE `show_up`.`ShowId` = '{$show_id}' 
                                                                       AND `show_up`.`UserId` = `users`.`Id` 
                                        ORDER BY `show_up`.`UpDt` DESC LIMIT {$limit_offset},{$page_size} ");
        if ($result !== false) {
            $fetch_result = db_fetch_list($result, $rows);
            return $rows;
        } else {
            return db_error();
        }
    }

    /**
     * 秀的评论保存 成功返回插入的Id 错误返回错误信息
     * @param int 秀Id
     * @param int 本评论回复的对象id 为0直接发表
     * @param string 评论的文本
     */
    function show_comment_save($show_id, $reply_id, $comment)
    {
        if (!is_numeric($show_id) || !is_numeric($reply_id)) {
            return "错误:评论保存信息错误";
        }
        $c = urldecode($comment);
        $c = db_escape($c);
        if (mb_strlen($c, 'utf8') > 135) {
            return "错误:提交的评论长度超过135字符";
        }
        if ($c !== false) {
            db_begin();
            $show_msg_result = db_query("SELECT `Author`,`CommentCount` FROM `shoe_show` WHERE `Id` = {$show_id} FOR UPDATE");
            if ($show_msg_result === false) {
                return db_rollback();
            }
            if ($show_msg = $show_msg_result->fetch_object()) {
            } else {
                db_commit();
                return "错误:未找到要评论的鞋主秀";
            }
            $comment_count = $show_msg->CommentCount + 1;
            $result1 = db_query("INSERT INTO `show_comment` SET 
                                                        `ShowId` = '{$show_id}',
                                                        `UserId` = '{$_SESSION['user_id']}',
                                                        `ReplyId` = '{$reply_id}',
                                                        `Text` = '{$c}'");
            if ($result1 !== true) {
                return db_rollback();
            }
            $comment_id = db_insert_id();
            //更新鞋主秀的评论数、作者被评论的总数以及推送消息数
            $result2 = db_query("UPDATE `users`,`shoe_show`,`message_count` SET 
                                            `shoe_show`.`CommentCount` = {$comment_count} ,
                                            `users`.`CommentCount` = `users`.`CommentCount` + 1,
                                            `message_count`.`Comment` = `message_count`.`Comment` + 1,
                                            `message_count`.`AllComment` = `message_count`.`AllComment` + 1
                                            WHERE `shoe_show`.`Id` = {$show_id} AND 
                                            `users`.`Id` = {$show_msg->Author} AND 
                                            `message_count`.`UserId` = {$show_msg->Author}");
            if ($result2 !== true) {
                return db_rollback();
            }
            //推送消息到作者
            $resul5 = db_query("INSERT INTO `message_comment` 
                                SET `Type` = 2,`MsgIdFrom` = {$comment_id},`UserId` = {$show_msg->Author}");
            if ($resul5 !== true) {
                return db_rollback();
            }

            $op = new user_operate();
            $result1 = $op->operate_save($op::ShoeShowComment, $_SESSION['user_id'], $comment_id);
            if ($result1 !== TRUE) {
                db_rollback();
                return $result1;
            }

            db_commit();
            return $comment_count;
        } else {
            return "错误:评论的文本不合法";
        }
    }

    /**
     * 秀的评论点赞 成功返回1 取消点赞返回-1 错误返回错误信息
     * @param int 评论Id
     */
    function show_comment_up($comment_id)
    {
        if (!is_numeric($comment_id)) {
            return "错误:评论点赞信息提交错误";
        }
        $result = 1;
        $update_type = '+';
        db_begin();
        $result1 = db_query
        ("INSERT INTO `show_comment_up` SET `CommentId` = {$comment_id},`UserId` = {$_SESSION['user_id']}");

        if ($result1 !== true) {
            if (db_errno() === 1062) //已经推荐过 则取消推荐
            {
                $result = -1;
                $update_type = '-';
                $result2 = db_query("DELETE FROM `show_comment_up` WHERE  
                                                `CommentId` = {$comment_id} AND 
                                                `UserId` = {$_SESSION['user_id']}");
                if ($result2 !== true) {
                    return db_rollback();
                }
            } else {
                return db_rollback();
            }
        }

        $result1 = db_query("UPDATE `show_comment` SET `UpCount` = `UpCount` {$update_type} 1 
                                                    WHERE `Id` = {$comment_id}");
        if ($result1 !== true) {
            return db_rollback();
        }

        $op = new user_operate();
        $result1 = $op->operate_save($op::ShoeShowUp, $_SESSION['user_id'], $comment_id);
        if ($result1 !== TRUE) {
            db_rollback();
            return $result1;
        }

        db_commit();
        return $result;
    }

    /**
     * 秀的评论举报 成功返回true 错误返回错误信息
     * @param int 评论Id
     */
    function show_comment_report($comment_id)
    {
        if (!is_numeric($comment_id)) {
            return "错误:评论举报信息提交错误";
        }
        db_begin();
        $result = db_query("INSERT INTO `show_comment_report` 
                            SET `CommentId` = '{$comment_id}',`UserId` = '{$_SESSION['user_id']}'");
        if ($result === FALSE) return db_rollback();
        $op = new user_operate();
        $result1 = $op->operate_save($op::ShoeShowUp, $_SESSION['user_id'], $comment_id);
        if ($result1 !== TRUE) {
            db_rollback();
            return $result1;
        }
        return true;
    }

    /**
     * 删除评论 成功返回'1' 失败返回错误信息
     * @param int $comment_id 评论Id
     * @param int $user_id 用户Id
     */
    function show_comment_dele($comment_id, $user_id)
    {
        if (!is_numeric($comment_id) || !is_numeric($user_id)) {
            return "作品评论删除时，提交的信息错误";
        }
        $check_ok = FALSE;
        $row;
        $result_sele1 = db_query("SELECT `shoe_show`.`Id`,`shoe_show`.`Author`,`show_comment`.`UserId` 
		                                    FROM `shoe_show`,`show_comment` 
		                                    WHERE `show_comment`.`Id` = {$comment_id} AND 
		                                          `shoe_show`.`Id` = `show_comment`.`ShowId`");
        if ($result_sele1 !== FALSE) {
            if ($row = $result_sele1->fetch_object()) {
                //作品作者和评论者可以删除
                if ($row->Author == $user_id || $row->UserId == $user_id) {
                    $check_ok = TRUE;
                }
            }
        }
        if ($_SESSION['user_level'] >= 90) { //如果为管理员可以删除
            $check_ok = TRUE;
        }
        if ($check_ok == TRUE) {
            db_begin();
            //删除评论
            $result1 = db_query("DELETE FROM `show_comment`
			                               WHERE `show_comment`.`Id` = {$comment_id}");

            if ($result1 !== TRUE) {
                return db_rollback();
            }
            if (db_affected_rows() > 0) {
                //更新作品的评论数、作者被评论的总数
                $result2 = db_query("UPDATE `users`,`shoe_show` SET 
                                     `shoe_show`.`CommentCount` = `shoe_show`.`CommentCount` - 1,
                                     `users`.`CommentCount` = `users`.`CommentCount` - 1 
                                     WHERE `shoe_show`.`Id` = {$row->Id} AND 
                                            `users`.`Id` = {$row->Author}");
                if ($result2 !== TRUE) {
                    return db_rollback();
                }
            }
            //删除评论点赞、评论举报、作者的被推送的评论消息
            $result3 = db_query("DELETE FROM `show_comment_up` WHERE `CommentId` = {$comment_id}");
            $result4 = db_query("DELETE FROM `show_comment_report` WHERE `CommentId` = {$comment_id}");
            $result5 = db_query("DELETE FROM `message_comment` 
                                 WHERE `Type` = 2 AND `MsgIdFrom` = {$comment_id} AND 
                                       `UserId` = {$row->Author}");
            if ($result3 !== TRUE || $result4 !== TRUE || $result5 !== TRUE) {
                return db_rollback();
            }
            $deleCount = db_affected_rows();
            if ($deleCount > 0) {
                $update_row = array();
                $update_row['UserId'] = $row->Author;
                $update_row['AllComment'] = "`AllComment` - {$deleCount}";
                $result6 = db_update('message_count', $update_row, 'UserId');
                if ($result6 !== TRUE) return db_rollback();
            }
            db_commit();
            return '1';
        } else {
            return '无权限删除此评论';
        }
    }

    /**
     * 删除鞋主秀 成功返回'1' 失败返回错误信息
     * @param int $shoe_show_id 作品Id
     * @param string $root 鞋主秀图片的路径最后含'/'
     */
    function show_dele($shoe_show_id, $root)
    {
        if (!is_numeric($shoe_show_id)) {
            return '错误:提交的鞋主秀信息错误';
        }
        //检查当前用户是否为管理员
        if (!isset($_SESSION['user_level']) || $_SESSION['user_level'] < 90) {
            return '无权限删除鞋主秀';
        }
        db_begin();
        //获取本鞋主秀信息
        $result_sele = db_query("SELECT * FROM `shoe_show` WHERE `Id` = {$shoe_show_id} FOR UPDATE");
        if ($result_sele !== FALSE) {
            if ($result_sele->num_rows > 0 && $shoeShowMsg = $result_sele->fetch_object()) {

            } else {
                return '未查询到要删除的鞋主秀';
            }
        } else {
            return db_rollback();
        }
        //删除掉鞋主秀
        $result_dele = db_query("DELETE FROM `shoe_show` WHERE `Id` = {$shoe_show_id}");
        if ($result_dele === FALSE) {
            return db_rollback();
        }
        if (db_affected_rows() <= 0) {
            return '未找到要删除的鞋主秀';
        }
        //查找本鞋主秀下的评论
        $result = db_query("SELECT `Id` FROM `show_comment` WHERE `ShowId` = {$shoe_show_id}");
        if ($result !== FALSE) {
            while ($row = $result->fetch_object()) {
                //删除鞋主秀作者的评论推送消息
                $result_dele = db_query("DELETE FROM `message_comment` 
                                         WHERE `Type` = 2 AND `MsgIdFrom` = {$row->Id} AND 
                                               `UserId`={$shoeShowMsg->Author}");
                if ($result_dele === FALSE) {
                    return db_rollback();
                }
                $deleCount = db_affected_rows();
                if ($deleCount > 0) {
                    $update_row = array();
                    $update_row['UserId'] = $shoeShowMsg->Author;
                    $update_row['AllComment'] = "`AllComment` - {$deleCount}";
                    $result6 = db_update('message_count', $update_row, 'UserId');
                    if ($result6 !== TRUE) return db_rollback();
                }

                //删除评论的点赞
                $result_dele = db_query("DELETE FROM `show_comment_up` 
				                                          WHERE `CommentId` = {$row->Id}");
                if ($result_dele === FALSE) {
                    return db_rollback();
                }
                //删除评论的举报
                $result_dele = db_query("DELETE FROM `show_comment_report` 
				                                          WHERE `CommentId` = {$row->Id}");
                if ($result_dele === FALSE) {
                    return db_rollback();
                }
            }
        } else {
            return db_rollback();
        }
        //删除本鞋主秀下的评论
        $result_dele = db_query("DELETE FROM `show_comment` 
		                                          WHERE `ShowId` = {$shoe_show_id}");
        if ($result_dele === FALSE) {
            return db_rollback();
        }

        //删除鞋主秀的操作信息 各用户对此鞋主秀的操作消息（动态） 例如评论、推荐 将在用户查看动态时如果查询不到相应记录则删除

        //删除用户的收藏
        $result_dele = db_query("DELETE FROM `user_collect` 
		                                          WHERE `Type` = 1 AND `CollectId` = {$shoe_show_id}");
        if ($result_dele === FALSE) {
            return db_rollback();
        }
        //删除鞋主秀的举报
        $result_dele = db_query("DELETE FROM `show_report` 
		                                          WHERE `ShowId` = {$shoe_show_id}");
        if ($result_dele === FALSE) {
            return db_rollback();
        }
        //删除鞋主秀的推荐
        $result_dele = db_query("DELETE FROM `show_up` 
		                                          WHERE `ShowId` = {$shoe_show_id}");
        if ($result_dele === FALSE) {
            return db_rollback();
        }
        //删除鞋主秀的图片
        $shoeShowImgs = explode(';', rtrim($shoeShowMsg->Picture, ';'));
        foreach ($shoeShowImgs as $shoeShowImg) {
            //缩略图
            $fileName = $root . make_img_name::make_img_mini_name($shoeShowImg);
            if (file_exists($fileName)) {
                unlink($fileName);
            }
            //原图
            $fileName = $root . $shoeShowImg;
            if (file_exists($fileName)) {
                unlink($fileName);
            }
        }
        //以上操作全部正常
        db_commit();
        return '1';
    }

    /**
     * 保存秀内容 成功返回秀Id 错误返回错误信息
     */
    function show_save(&$data)
    {
        if (!isset($_SESSION["user_level"])) {
            return "错误:请登录";
        }
        if (!isset($data["shoe_show_state"]) || ($data["shoe_show_state"] != 1 && $data["shoe_show_state"] != 0)) {
            return "错误:提交的秀状态不允许";
        } else if (!isset($data['introd'])) {
            return "错误:提交的秀信息不完全";
        }

        $data['introd'] = db_escape(urldecode($data['introd']));
        $introd_len = mb_strlen($data['introd'], 'utf8');
        if ($introd_len > 135) {
            return "错误:提交的秀描述长度超过135字符";
        } elseif ($introd_len < 4) {
            return "错误:提交的秀描述长度小于4字符";
        }
        // 需要提供所属作品的id
        if (!isset($data["work_id"]) || !is_numeric($data["work_id"])) {
            return "错误:页面信息有误";
        }
        // 保存为草稿可以不需要图片
        if ($data['shoe_show_state'] == 1 && empty($data["shoe_show_img_names"])) {
            return "错误:鞋主秀尚未提交图片";
        }
        //20170112 添加 检查提交的作品是否存在
        db_begin();
        $sql_str = "SELECT `Id`,`Name`,`ShowMaxIndex` FROM `works` WHERE `Id` = {$data['work_id']} FOR UPDATE";
        $result = db_query($sql_str);
        if ($result instanceof mysqli_result) {
            if ($result->num_rows > 0 && $workMsg = $result->fetch_object()) {
                //none
            } else {
                return '错误:未找到相关的作品信息';
            }
        } else {
            return db_error();
        }
        //20170112 添加 所属作品名与简介的搜索分词
        global $CfgPara;
        require_once("{$CfgPara->root}/class/keyword_zh.func.php");
        $keyWord = get_keywords("{$workMsg->Name} {$data['introd']}");
        if (isset($data["shoe_show_id"]) && is_numeric($data["shoe_show_id"]) && $data["shoe_show_id"] > 0) //更新
        {
            return $this->show_edit_update($data, $keyWord);
        } else //插入
        {
            return $this->show_edit_insert($data, $keyWord, $workMsg);
        }
    }

    function show_edit_update(&$data, &$keyWord)
    {
        if (!is_numeric($data["shoe_show_id"])) {
            return "错误:提交的秀信息错误";
        }
        if ($_SESSION["user_level"] < 90) //当前用户非管理员
        {
            $show_msg = $this->show_msg($data["shoe_show_id"]);
            if (is_string($show_msg) || $show_msg === false) //查询错误
            {
                return "错误:无法查询到该鞋秀";
            } else {
                if (!isset($_SESSION["user_id"]) || !isset($_SESSION["user_level"])) {
                    return "错误:无权限管理此鞋主秀";
                }
                //仅作者和管理员可编辑
                if ($show_msg->Author != $_SESSION["user_id"] && $_SESSION["user_level"] < 90) {
                    return "错误:无权限管理此鞋主秀";
                }
            }
        }
        // 数据库连接在上级函数中已提交事务开始
        global $CfgPara;
        $imgs = do_edit_img(
            3, $data["shoe_show_img_names"],
            "{$CfgPara->root}/shoe_show_pic/", 'shoe_show', 'Picture', $data["shoe_show_id"]);
        if ($imgs === false) {
            return '处理上传图片时错误';
        }
        $sql_str = '';
        // 如果当前状态为草稿 而 修改后状态为发布 将草稿数量加1 已发布的数量减1
        if ($show_msg->State == 1 && $data['shoe_show_state'] == 0) {
            $fname[0] = 'ShowCount';
            $fname[1] = 'ShowDraftCount';
            $state_change = 1; //状态将会改变 需要将作者的发布作品数与草稿作品数更新
        }
        // 如果当前状态为草稿 而 修改后状态为发布 则需要检测余额 然后付费
        // 并将草稿数量减1 已发布的数量加1
        elseif ($show_msg->State == 0 && $data['shoe_show_state'] == 1) {
            $fname[0] = 'ShowDraftCount';
            $fname[1] = 'ShowCount';
            $state_change = 1; //状态将会改变 需要将作者的发布作品数与草稿作品数更新
            // 20170406 新增 发布鞋主秀要余额2元 如果在界面时选择的是第三方支付工具
            // 例如微信、支付宝 在此函数前已经将钱加入余额中
            if (!isset ($_SESSION['user_id'])) return '发布鞋主秀前，请登陆';
            // 连接支付类
            if ($data['shoe_show_state'] == 1) {
                require_once("{$CfgPara->root}/class/pay.class.php");
                $myPay = new CPay();
                $result = $myPay->pay_submit(CPay::PayToolBalance, CPay::GoodsPrice_ShowRelease, 1);
                if ($result == 0) {
                    $data['shoe_show_state'] = 0; //余额不足 存为草稿
                    $balance_no = 1;
                    $state_change = 0;
                } elseif ($result != 1) {
                    db_rollback();
                    return $result;
                }
            }
        }

        if (isset ($fname) && $state_change == 1) {
            $sql_str = "UPDATE `works` 
                        SET `{$fname[0]}` = `{$fname[0]}` - 1,
                            `{$fname[1]}` = `{$fname[1]}` + 1
                        WHERE `Id` = {$data['work_id']}";
            $result = db_query($sql_str);
            if ($result !== TRUE) return db_rollback();
        }

        // 更新鞋主秀信息
        $sql_str = "UPDATE `shoe_show` 
                    SET 
                    `Author` = '{$_SESSION['user_id']}',
                    `Picture` = '{$imgs}',
                    `Introd`='{$data['introd']}',
                    `State`='{$data['shoe_show_state']}',
                    `Keyword`='{$keyWord}'";
        $sql_str .= " WHERE `Id` = '{$data['shoe_show_id']}'";
        $result = db_query($sql_str);
        if ($result !== TRUE) return db_rollback();

        // 进行操作记录 可以在个人动态中查看
        if ($shoeShowMsg->State == 0 && $data['shoe_show_state'] == 1) {
            $op = new user_operate();
            $result1 = $op->operate_save($op::ShoeShowRelease, $_SESSION['user_id'], $data['shoe_show_id']);
            if ($result1 !== TRUE) {
                db_rollback();
                return $result1;
            }
        }

        // 提交事务
        db_commit();
        if (isset($balance_no) && $balance_no == 1) {
            return "0|您的余额不足或支付失败，已保存为草稿";
        } elseif ($data['shoe_show_state'] == 0) {
            return "0|鞋主秀已保存为草稿";
        }
        return "1|鞋主秀已发布完成";
    }

    /**
     * 获取鞋秀信息 正确返回对象，错误返回错误信息
     * @param int $shoe_show_id 秀Id
     */
    public function show_msg($shoe_show_id)
    {
        if (!is_numeric($shoe_show_id)) {
            return "错误:提交的鞋主秀信息错误";
        }
        //先查询鞋主秀相关内容 避免当时作品已删除 但是鞋主秀还保留的情况
        $sql_str = "SELECT `shoe_show`.*,
				    date_format(`shoe_show`.`ReleaseDt`,'%Y.%m.%d') as ReleaseDate, 
                    `users`.`Name` as UserName, `users`.`Avatar` as UserAvatar 
                    FROM `shoe_show`,`users` 
                    WHERE `shoe_show`.`Id` = '{$shoe_show_id}' 
                    AND `shoe_show`.`Author` = `users`.`Id` ";
        //return $sql_str;
        $result1 = db_query($sql_str);
        if ($result1 instanceof mysqli_result) {
            if ($result = $result1->fetch_object()) {
                //return $result;
            } else {
                return '未查询到此鞋主秀';
            }
        } else {
            return db_error();
        }
        if (!isset($result->WorkId)) return '未查询到此鞋主秀';
        //再查询鞋主秀所属作品的相关内容
        $sql_str = "SELECT `Name`,`Picture`,`Introd` 
                    FROM `works` 
                    WHERE `Id` = '{$result->WorkId}'";
        $result1 = db_query($sql_str);
        if ($result1 !== FALSE && $result1->num_rows > 0) {
            if ($result_workMsg = $result1->fetch_object()) {
                $result->WorkName = $result_workMsg->Name;
                $result->WorkPicture = $result_workMsg->Picture;
                $result->WorkIntrod = $result_workMsg->Introd;
            }
        }
        return $result;
    }

    function show_edit_insert(&$data, &$keyWord, &$workMsg)
    {
        // 检查当前用户是否已在作品下有鞋主秀
        $sql_str = "SELECT * FROM `shoe_show` 
                    WHERE `WorkId` = {$data['work_id']} AND 
                          `Author` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result === FALSE) return db_error();
        if ($result->num_rows > 0) {
            return '您已有关于此作品的鞋主秀';
        }

        global $CfgPara;
        $imgs = do_edit_img(
            3, $data["shoe_show_img_names"],
            "{$CfgPara->root}/shoe_show_pic/", 'shoe_show', 'Picture');

        // 20170405 新增 发布作品需要余额2元 如果在界面时选择的是第三方支付工具 
        // 例如微信、支付宝 在此函数前已经将钱加入余额中
        if (!isset ($_SESSION['user_id'])) return '发布作品前，请登陆';
        // 连接支付类
        if ($data['shoe_show_state'] == 1) {
            require_once("{$CfgPara->root}/class/pay.class.php");
            $myPay = new CPay();
            $result = $myPay->pay_submit(CPay::PayToolBalance, CPay::GoodsPrice_ShowRelease, 1);
            if ($result == 0) {
                $data['shoe_show_state'] = 0; //余额不足 存为草稿
                $balance_no = 1;
            } elseif ($result != 1) {
                db_rollback();
                return $result;
            }
        }

        // 更新作品的鞋主秀发布或草稿数量,以及鞋主秀的最大索引
        $show_max_index = (int)$workMsg->ShowMaxIndex + 1;
        if ($data['shoe_show_state'] == 1) {
            $fname = 'ShowCount';
        } else {
            $fname = 'ShowDraftCount';
        }
        $sql_str = "UPDATE `works` 
                    SET `ShowMaxIndex` = {$show_max_index},
                        `{$fname}` = `{$fname}` + 1 
                    WHERE `Id` = {$workMsg->Id}";
        $result = db_query($sql_str);
        if ($result != TRUE) return db_rollback();

        // 插入鞋主秀信息
        $sql_str = "INSERT INTO `shoe_show` SET 
                    `Author` = '{$_SESSION['user_id']}',
                    `Picture` = '{$imgs}',
                    `Introd` = '{$data['introd']}',
                    `WorkId` = {$data['work_id']},
                    `State` = {$data['shoe_show_state']},
                    `Keyword` = '{$keyWord}',
                    `WorkIndex` = {$show_max_index}";
        $result = db_query($sql_str);
        if ($result !== TRUE) return db_rollback();
        $show_id = db_insert_id();
        if ($data['shoe_show_state'] == 1) {
            $op = new user_operate();
            $result1 = $op->operate_save($op::ShoeShowRelease, $_SESSION['user_id'], $show_id);
            if ($result1 !== TRUE) {
                db_rollback();
                return $result1;
            }
        }

        // 提交事务
        db_commit();
        if (isset($balance_no) && $balance_no == 1) {
            return "0|您的余额不足或支付失败，已保存为草稿";
        } elseif ($data['shoe_show_state'] == 0) {
            return "0|鞋主秀已保存为草稿";
        }
        return "1|鞋主秀已发布完成";
    }

    /**
     * 鞋主秀发布 将原为草稿的秀直接发布 其它都不修改 成功返回1 如果原本已发布返回0 失败返回错误信息
     * @param int $show_id 鞋主秀id
     * @param string $order_id 订单号
     * @param CPay $pay 支付操作类
     */
    function show_edit_release($show_id, &$order_id, &$pay)
    {
        if (!is_numeric($show_id)) {
            return "鞋主秀发布时，提交的信息错误";
        }
        if (!isset($order_id)) {
            return "鞋主秀发布时，提交的订单号错误";
        }
        $show_msg = $this->show_msg($show_id);
        if (is_string($show_msg) || $show_msg === false) //查询错误
        {
            return "鞋主秀发布时 无法查询到该鞋秀";
        }
        if ($show_msg->State == 1) {
            return 0;
        }
        // db_begin(); 20171119 此处事务由上层调用者管理
        // 更新所属作品的鞋主秀数量
        $sql_str = "UPDATE `works` 
                    SET `ShowCount` = `ShowCount` + 1,
                        `ShowDraftCount` = `ShowDraftCount` - 1
                    WHERE `Id` = {$show_msg->WorkId}";
        $result = db_query($sql_str);
        if ($result !== TRUE) return db_error();
        // 更新鞋主秀信息
        $sql_str = "UPDATE `shoe_show` 
                    SET `State`='1'
                    WHERE `Id` = '{$show_id}'";
        $result = db_query($sql_str);
        if ($result !== TRUE) return db_error();
        // 插入消费记录
        $result = $pay->consume_insert(CPay::ConsumeType_ShowRelease, CPay::GoodsPrice_ShowRelease, $order_id);
        if ($result != 1) {
            return $result;
        }

        // 消费数据统计更新
        $result = $pay->consume_count_record(CPay::GoodsPrice_ShowRelease, CPay::ConsumeType_ShowRelease);
        if ($result !== 1) return db_error();
        $op = new user_operate();
        $result = $op->operate_save($op::ShoeShowRelease, $_SESSION['user_id'], $show_id);
        if ($result !== TRUE) {
            return $result;
        }
        // db_commit(); 20171119 此处事务由上层调用者管理
        return 1;
    }

    /**
     * 鞋主秀主页浏览数计数自增1 正确返回true 错误返回错误信息
     * @param int $show_id 秀的id
     * @return bool|string
     */
    function show_view_count($show_id)
    {
        if (!is_numeric($show_id)) {
            return '错误: 提交的鞋主秀主页信息不正确';
        }
        $sql_str = "UPDATE `shoe_show` 
                    SET `ViewCount` = `ViewCount` + 1 
                    WHERE `Id` = {$show_id}";
        $result = db_query($sql_str);
        if ($result === TRUE) {
            return TRUE;
        } else {
            return db_error();
        }
    }

    /**
     * 鞋主秀主页浏览数计数自增1 正确返回true 错误返回错误信息
     * @param int $work_id 秀所属作品的id
     * @param int $work_index 秀在作品中的索引
     * @return bool|string
     */
    function show_view_count2($work_id, $work_index)
    {
        if (!is_numeric($work_id) || !is_numeric($work_index)) {
            return '错误: 提交的鞋主秀主页信息不正确';
        }
        $sql_str = "UPDATE `shoe_show` 
                    SET `ViewCount` = `ViewCount` + 1 
                    WHERE `WorkId` = {$work_id} AND
                          `WorkIndex` = {$work_index}";
        $result = db_query($sql_str);
        if ($result === TRUE) {
            return TRUE;
        } else {
            return db_error();
        }
    }

    function comment_up_check($comment_id)
    {
        if (!isset($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return false;
        }
        if (!is_numeric($comment_id)) {
            return "检查评论是否已赞时:提交的信息错误";
        }
        $result = db_query("SELECT `CommentId` FROM `show_comment_up` WHERE `CommentId` = {$comment_id} AND `UserId` = {$_SESSION['user_id']}");
        if ($result !== false && $result->num_rows > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检测当前用户是否已参与鞋主秀的推荐 错误时提示错误信息
     * @param int $show_id
     * @return bool|string
     */
    function show_recommend_check($show_id)
    {
        if (!isset($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return false;
        }
        if (!is_numeric($show_id)) {
            return "检查是否已推荐时:提交的信息错误";
        }
        $result = db_query("SELECT `ShowId` FROM `show_up` WHERE `ShowId` = {$show_id} AND `UserId` = {$_SESSION['user_id']}");
        if ($result !== false && $result->num_rows > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检测当前用户是否已参与鞋主秀的评论 错误时提示错误信息
     * @param int $show_id
     * @return bool|string
     */
    function show_comment_check($show_id)
    {
        if (!isset($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return false;
        }
        if (!is_numeric($show_id)) {
            return "检查是否已评论时:提交的信息错误";
        }
        $result = db_query("SELECT `ShowId` FROM `show_comment` WHERE `ShowId` = {$show_id} AND `UserId` = {$_SESSION['user_id']} LIMIT 1");
        if ($result !== false && $result->num_rows > 0) {
            return true;
        } else {
            return false;
        }
    }
}
